//
//  NgrmapViewController.m
//  sdk2.0zhengquandasha
//
//  Created by peng on 15/10/19.
//  Copyright © 2015年 palmaplus. All rights reserved.
//

#import "NgrmapViewController.h"
#import "SelectStartingAndEndPoint.h"
#import "NavigationView.h"
#import "PointView.h"
//#import <Nagrand/NGROverlayer.h>
#import "SearchViewController.h"
#import "CompassView.h"
#import "MBProgressHUD.h"
#import "locationStyleView.h"
#import "RealTimeNavigationView.h"
#import "setStartAndEndPointView.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "PlottingScaleView.h"
#import <CoreLocation/CoreLocation.h>
#import "KeyWindowView.h"
#import "ChoseMapStyleView.h"
#import "AppDelegate.h"
#import "EdgeView.h"
//#import "ChangeLocationStyleView.h"

#define SCREENBOUNDS [UIScreen mainScreen].bounds
#define kScreenHeight   [[UIScreen mainScreen] bounds].size.height
#define kScreenWidth    [[UIScreen mainScreen] bounds].size.width
#define ratioX(x) ([UIScreen mainScreen].bounds.size.width/320.0 )* x
#define ratioY(y) ([UIScreen mainScreen].bounds.size.height/568.0 )* y





@interface NgrmapViewController ()<NGRDataSourceDelegate,NGRMapViewDelegate,NGRNavigateManagerDelegate,UIActionSheetDelegate,NGRPositioningDelegate,UITableViewDataSource,UITableViewDelegate,NavigationViewDelegate,CLLocationManagerDelegate,MBProgressHUDDelegate,UIAlertViewDelegate,CBPeripheralManagerDelegate,PhoneMacAddressDelegate>{
    
    NGRDataSource *_dataSource;
    
    NGRFeatureLayer* _NgrFeatureLayerLocation;

//    NGRFeatureLayer* _positionLayer;

    BOOL _floorFlag;
    
    UIButton* _floorChangeButton;
    
    UITableView* _tableViewOfFloors;
    
    NSString* _currentFloorName;
    
    NGRID _currentFloorId;
    
//    touchPointData* _startFloorData;
//    touchPointData* _endFloorData;
  
    CGPoint _currentLocationPoint;
    
    NGRNavigateManager *_navigationManager;
    
    NGRFeatureLayer *_naviLayer;
    
    NSMutableArray* _floorDataArray;
    NSMutableArray* _floorNumberDataArray;
    float _startY;
    
    UIButton* _btnSubtract;
    
    UIButton* _btnAdd;
    UIButton* _Locationbtn;
    BOOL oldLocationFlag;

    SelectStartingAndEndPoint *_selectStartAndEndPintView;//点击弹出底部界面
    
//    NGROverlayer *_selectPinOverlayer;
//    NGROverlayer *_selectStartOverlayer;
//    NGROverlayer *_selectEndOverlayer;
    
     UIView* _bottomView;
    
    NavigationView* _navigationView;
    
    UIImageView* _arrowImageView;
    
    NGRPositioningManager* _blueManager;
    
    NGRPositioningManager* _wifiManager;
    
    UISegmentedControl* _segmentedControl;

    NGRLocation *_currentLocation;
    
    
    CGPoint  _Locationbtncenter ;
    CGPoint  _btnAddcenter;
    CGPoint  _floorChangeButtoncenter;
    CGPoint  _btnSubtractcenter ;
    CGPoint  _segmentedControlcenter;
    
    UIScrollView* _publicFacilitiesView;
  //  NGROverlayer* _redView ;
    
    MBProgressHUD *HUD;
    
    UITapGestureRecognizer *_tapGesture;
    //搜索视图控制器
    SearchViewController *_searchVC;
     /** 切换定位方式的视图 */
   // tempView *_tempView;
    /** 实时导航的视图 */
    RealTimeNavigationView *_realTimeView;
     /** 当前的选择的定位方式 */
    LocationStyle _currentLocationStyle;
    /** 当前的定位点 */
    NGROverlayer *_locationOverLayer;
    /** 是否正在定位 */
    BOOL  isLoctioning;
    
    BOOL plotScaleUp;
    CGFloat _currentAngleMap;
    CGFloat _currentAngleDevice;
    
}
@property (strong,nonatomic)UIActivityIndicatorView*  activityView;

 /** 指南针视图 */
@property (strong,nonatomic)CompassView *compassView;
  /** 设置导航起点和终点的视图 */
@property (strong,nonatomic)setStartAndEndPointView *setStartAndEndPointView;
/** 检测设备蓝牙是否开启 */
@property (strong,nonatomic)CBPeripheralManager *manager;
/** 比例尺 */
@property (strong,nonatomic)PlottingScaleView *plottingView;
/**  */
@property (strong,nonatomic)CLLocationManager *cllocationManger;


@property (assign,nonatomic)BOOL isShowCollect;
@end

@implementation NgrmapViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigationBar];
    [AppDelegate sharedAppdelegate].delegate = self;
    plotScaleUp = false;

    isLoctioning = NO;
    
    [self configMapView:nil];
    
    _floorDataArray = [NSMutableArray array];
    _floorNumberDataArray = [NSMutableArray array];
     _currentFloorName = @"F15";//13526604 3663425.75  ／／13526605 3663426.25

//    self.automaticallyAdjustsScrollViewInsets = NO;
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"标题-2"] forBarMetrics:UIBarMetricsDefault];
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor colorWithRed:200 green:200 blue:200 alpha:1],[UIFont boldSystemFontOfSize:20.0f], nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName,NSFontAttributeName, nil]];
    self.navigationController.navigationBar.titleTextAttributes = dict;

    
    self.title = @"上海图聚办公室";


    [self addMapData];
    
    [self addBottomToolBar];
    
    [self addFloorChangeButton];
    
    [self addZoomSubtractButton];

    [self addZoomAddButton];

    [self addLocationButton];
    
    [self addChangeFloorTableView];
    
    
    [self addPoiIcon];
    [self addPoiSearchButton];
    [self.mapView setMaxZoom:0.1];
    UILabel* iconLabel = [[UILabel alloc]init];
    iconLabel.text = @"数据服务：";
    iconLabel.frame = CGRectMake(kScreenWidth-100, 64, 50, 20);
    iconLabel.font = [UIFont systemFontOfSize:8];
    UILabel* iconLabel1 = [[UILabel alloc]init];
    iconLabel1.text = @"图聚Palmap+";
    iconLabel1.frame = CGRectMake(kScreenWidth-60,  64, 50, 20);
    iconLabel1.font = [UIFont systemFontOfSize:7];
    iconLabel1.textColor = [UIColor colorWithRed:58.0/255.0 green:149.0/255.0 blue:174.0/255.0 alpha:1];
    
     [self addRationPoint];
    
    [self MoveDownNOAnimate];
    //添加指南针视图
    self.compassView = [[CompassView alloc]init];
    [self.view addSubview:self.compassView];

    
    [self tapGestureCreate];
    
    [self addChangeLocationStyleBtn];

    
   // _navigationManager = [[NGRNavigateManager alloc]init];
    _navigationManager = [[NGRNavigateManager alloc]initWithUrl:@"211.161.101.67/nagrand-service/"];
    _navigationManager.delegate = self;
    //添加比例尺
    [self createPlottingView];
    //添加设备旋转支持
    [self createcollectionManger];
    //[self requestCategary];
    _isShowCollect = NO;
}

#pragma mark- 初始化navigationbar的样式
-(void)initNavigationBar{
//    for (UIView *View in self.navigationController.navigationBar.subviews) {
//        [View removeFromSuperview];
//    }
    [self.navigationController.navigationBar setBarTintColor:[UIColor blackColor]];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.size = CGSizeMake(25, 20);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"ico_menu"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
}
#pragma mark- 侧滑事件
-(void)leftAction:(UIButton *)btn{
    __weak typeof(self)weakSelf = self;
//    [[KeyWindowView sharedKeyWindowView].array addObject:@"aaaa"];
    EdgeView *leftView = [[[NSBundle mainBundle] loadNibNamed:@"EdgeView" owner:self options:nil] lastObject];
    leftView.frame = CGRectMake(-(KWIDTH - 50), 20, KWIDTH - 50, KHEIGHT - 20);
    leftView.curStyle = _currentLocationStyle;
    //开启定位
    BOOL start = [AppDelegate sharedAppdelegate].isFirstStart;
    leftView.startLocationBlock = ^(LocationStyle style){
        if (start) {
            [weakSelf startLocation:_currentLocationStyle];
            [AppDelegate sharedAppdelegate].isFirstStart = false;
        }else{
            [weakSelf stopLocation];
            _currentLocationStyle = style;
        }
    };
    
    [[KeyWindowView sharedKeyWindowView] addSubview:leftView];
    [KeyWindowView showWithAnimation:0.5 withAlpha:0.8];
    
    [UIView animateWithDuration:0.5 animations:^{
        leftView.frame = CGRectMake(0, leftView.y, leftView.width, leftView.height);
    }];

    
    
}

#pragma mark- PhoneMacAddressDelegate
//取得本机的mac地址后的回调
-(void)getPhoneMacAddressSuccess:(NSString *)phoneAddress{
    // [self startWifiLocation:LocationBluetooth];
}

#pragma mark- 请求categaryID
-(void)requestCategary{
    [_dataSource requestCategories:6 inLocation:6 success:^(NSArray *categories) {
        for (NGRCategoryModel * model in categories) {
            NSLog(@"%@%@%@%@",model.name1,model.name2,model.name3,model.name4);
        }
    } error:^(NSError *error) {
        
    }];
}

#pragma mark- 比例尺
-(void)createPlottingView{
    self.plottingView = [[PlottingScaleView alloc]initWithFrame:CGRectMake(10 + 50,_startY + 70, 60, 40)];
    self.plottingView.scaleNum = 10;
    self.plottingView.changeAbled = NO;
    [self.view addSubview:self.plottingView];
}


//添加设置起点终点的视图
#pragma mark- 添加设置起点终点的视图
-(void)addSetStartAndEndPointView{
    __weak typeof(self)weakSelf = self;
    __weak typeof(_navigationManager)weakNav = _navigationManager;
    _setStartAndEndPointView = [[setStartAndEndPointView alloc]initWithFrame:CGRectMake(0  , KHEIGHT , KWIDTH, 64)];
    _setStartAndEndPointView.mapView = self.mapView;
    _setStartAndEndPointView.startNavigationBlock = ^{
        NSLog(@"开始导航");
        if (weakNav) {
            [SVProgressHUD showWithStatus:@"正在搜索"];
            [weakNav navigationFromPoint:weakSelf.setStartAndEndPointView.startPointOverLayer.worldPosition fromFloor:weakSelf.setStartAndEndPointView.startPointOverLayer.floorId toPoint:weakSelf.setStartAndEndPointView.endPointOverLayer.worldPosition toFloor:weakSelf.setStartAndEndPointView.endPointOverLayer.floorId];
        }
        
    };
    [self.view addSubview:_setStartAndEndPointView];
    
    [UIView animateWithDuration:0.5 animations:^{
        _setStartAndEndPointView.frame = CGRectMake(0  , KHEIGHT - 64 , KWIDTH, 64);
    }];
}


#pragma mark- 添加切换2D/3D按钮
-(void)addChangeLocationStyleBtn{
    
    CGSize btnSize = CGSizeMake(40, 40);
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(kScreenWidth - btnSize.width -10, 74 , btnSize.width, btnSize.height);
    [btn setBackgroundImage:[UIImage imageNamed:@"ico_map"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(changeLocationStyleAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

}

-(void)changeLocationStyleAction:(UIButton *)btn{
    CGFloat skew = self.mapView.skew;
    __weak typeof(self)weakSelf = self;
//    if (self.keyWindowView) {
//        [self.keyWindowView removeFromSuperview];
//        self.keyWindowView = nil;
//    }else
    
        ChoseMapStyleView *chose = [[[NSBundle mainBundle] loadNibNamed:@"ChoseMapStyleView" owner:self options:nil] lastObject];
        chose.showCollect = self.isShowCollect;
        if (skew != 0) {
            chose.currentStyle = mapShowStyle3d;
        }else{
            chose.currentStyle = mapShowStyle2d;
        }
        
        chose.choseMapStyle = ^(mapShowStyle style,BOOL showCollect){
            if (style == mapShowStyle2d) {
                //切换成2d
                [weakSelf.mapView skewAtAngle:0];
            }else if (style == mapShowStyle3d){
                //切换成3d
                [weakSelf.mapView skewAtAngle:60];
            }
            
            if (showCollect) {
                //展示收藏点
                NSLog(@"展示收藏点");
            }else{
                //隐藏收藏点
                NSLog(@"隐藏收藏点");
            }
            _isShowCollect = showCollect;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                sleep(0.5);
                    [KeyWindowView removeFromSuperView:0.0];
            });
        };
        chose.frame = CGRectMake(20, 124, KWIDTH - 40, KHEIGHT/3 + 30);
        chose.layer.cornerRadius = 10;
        chose.alpha = 1.0;
        chose.backgroundColor = [UIColor whiteColor];
        [[KeyWindowView sharedKeyWindowView] addSubview:chose];
          
        
        UIButton *btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
        btnCancel.frame = CGRectMake(CGRectGetMaxX(chose.frame) -40, chose.y - 50, 40, 40);
        
        [btnCancel setBackgroundImage:[UIImage imageNamed:@"ico_closs"] forState:UIControlStateNormal];
        [btnCancel addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
        [[KeyWindowView sharedKeyWindowView] addSubview:btnCancel];
        
//        [KeyWindowView sharedKeyWindowView].cancelBlock = ^{
//            [KeyWindowView removeFromSuperView:0.3];
//        };
    
}

-(void)cancelAction{
    [KeyWindowView removeFromSuperView:0.0];
}

-(void)addPoiSearchButton{
    UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightbutton addTarget:self action:@selector(searchTarget) forControlEvents:UIControlEventTouchUpInside];
    rightbutton.frame = CGRectMake(0, 0, 20, 20);
    [rightbutton setBackgroundImage:[UIImage imageNamed:@"Search_181px_1190971_easyicon.net"] forState:UIControlStateNormal];
    
    UIBarButtonItem* rightBarbutton = [[UIBarButtonItem alloc]initWithCustomView:rightbutton];
    self.navigationItem.rightBarButtonItem = rightBarbutton;
    
    self.navigationController.navigationBar.tintColor =[UIColor whiteColor];
    
}

#pragma mark- 搜索poi
-(void)searchTarget{
     _searchVC = [[SearchViewController alloc]init];
//    _searchVC.delegate = self;
    __weak typeof (_dataSource)weakDataSource = _dataSource;
    _searchVC.poiSearchBlock = ^(NSString * keyWord){
        NSLog(@"开始搜索%@",keyWord);
        sleep(1);
        [weakDataSource searchPOI:keyWord start:0 count:5 parents:nil categories:nil];
    };
    [self.navigationController pushViewController:_searchVC animated:YES];
}
-(void)addPoiIcon{
 
    
    _publicFacilitiesView = [[UIScrollView alloc]initWithFrame:CGRectMake(kScreenWidth - 50, 74, 40, 85)];
    [self.mapView addSubview:_publicFacilitiesView];
    
    for (int i = 1; i<8; i++) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, i*(40+5), 40, 40);
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"0%d",i]] forState:UIControlStateNormal];
        [_publicFacilitiesView addSubview:button];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 19;
        button.layer.borderColor = [UIColor lightGrayColor].CGColor;
        button.layer.borderWidth = 1;
        button.alpha = 0.7;
        button.tag = i;
        [button addTarget:self action:@selector(publicFacilitiesViewSubViewButtonTarget:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
}
-(void)publicFacilitiesViewSubViewButtonTarget:(UIButton*)sender{
    [self.mapView visibleAllLayerFeature:@"Facility" isVisible:NO];
    switch (sender.tag) {
        case 1:{
            static BOOL flag;
            [self.mapView visibleAllLayerFeature:@"Facility" isVisible:YES];
            if (flag) {
                
                [ UIView animateWithDuration:0.5 animations:^{
                    _publicFacilitiesView.frame = CGRectMake(kScreenWidth - 50, 74, 40, 85);
                }];
            }else{
                [ UIView animateWithDuration:0.5 animations:^{
                    _publicFacilitiesView.frame = CGRectMake(kScreenWidth - 50, 74, 40, 374);
                }];
            }
            flag = !flag;
            
        }

            break;
        case 2:
        {
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(24091000) isVisible:YES];
        }
            
            break;
        case 3:
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(24093000) isVisible:YES];
            break;
        case 4:
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(23061000) isVisible:YES];
            break;
        case 5:
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(24097000) isVisible:YES];
            break;
        case 6:
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(23024000) isVisible:YES];
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(23025000) isVisible:YES];
          
            break;
        case 7:
            [self.mapView visibleAllLayerFeature:@"Facility" isVisible:YES];
            break;
        default:
            break;
    }
    
    
    
}

-(void)addRationPoint{
_Locationbtncenter = CGPointMake(_Locationbtn.center.x, _Locationbtn.center.y);
    
  _floorChangeButtoncenter = CGPointMake(_floorChangeButton.center.x, _floorChangeButton.center.y);
    
   _btnAddcenter = CGPointMake(_btnAdd.center.x, _btnAdd.center.y);
    
 _btnSubtractcenter = CGPointMake(_btnSubtract.center.x, _btnSubtract.center.y);
    
 _segmentedControlcenter = CGPointMake(_segmentedControl.center.x, _segmentedControl.center.y);

}
-(void)MoveDownNOAnimate{
    
        _Locationbtn.center = CGPointMake(_Locationbtncenter.x, _Locationbtncenter.y+ratioY(50));
        
        _floorChangeButton.center = CGPointMake(_floorChangeButtoncenter.x, _floorChangeButtoncenter.y+ratioY(50));
        
        _btnAdd.center = CGPointMake(_btnAddcenter.x, _btnAddcenter.y+ratioY(50));
        
        _btnSubtract.center = CGPointMake(_btnSubtractcenter.x, _btnSubtractcenter.y+ratioY(50));
        
        _segmentedControl.center = CGPointMake(_segmentedControlcenter.x, _segmentedControlcenter.y+ratioY(50));
        
    
    
}


-(void)MoveDown{
    
    [UIView animateWithDuration:0.3 animations:^{
        _Locationbtn.center = CGPointMake(_Locationbtncenter.x, _Locationbtncenter.y+ratioY(50));
        
        _floorChangeButton.center = CGPointMake(_floorChangeButtoncenter.x, _floorChangeButtoncenter.y+ratioY(50));
        
        _btnAdd.center = CGPointMake(_btnAddcenter.x, _btnAddcenter.y+ratioY(50));
        
        _btnSubtract.center = CGPointMake(_btnSubtractcenter.x, _btnSubtractcenter.y+ratioY(50));
        
        _segmentedControl.center = CGPointMake(_segmentedControlcenter.x, _segmentedControlcenter.y+ratioY(50));
        CGPoint point = self.plottingView.center;

        if (plotScaleUp) {
            self.plottingView.center = CGPointMake(point.x, point.y + 64);
            plotScaleUp = false;
        }



    }];
    
}

-(void)MoveUp{
    plotScaleUp = true;
    
    [UIView animateWithDuration:0.3 animations:^{
        _Locationbtn.center = CGPointMake(_Locationbtncenter.x, _Locationbtncenter.y);
        
        _floorChangeButton.center = CGPointMake(_floorChangeButtoncenter.x, _floorChangeButtoncenter.y);
        
        _btnAdd.center = CGPointMake(_btnAddcenter.x, _btnAddcenter.y);
        
        _btnSubtract.center = CGPointMake(_btnSubtractcenter.x, _btnSubtractcenter.y);
        
        _segmentedControl.center = CGPointMake(_segmentedControlcenter.x, _segmentedControlcenter.y);
        CGPoint point = self.plottingView.center;
        self.plottingView.center = CGPointMake( point.x, point.y - 64);
        
    }];
    
}

-(void)changeLocationEngineer{
        
}


-(void)addBottomToolBar{
    //_startY = kScreenHeight - ratioY(57);
    _startY = kScreenHeight - ratioY(70);
}
//-(void)changeMainView:(UIButton*)sender{
//    NSLog(@"");
//}


-(void)addZoomSubtractButton{
     _btnSubtract = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth-50, _startY, 40, 40)];
    
    [_btnSubtract setBackgroundColor:[UIColor whiteColor]];
    
    [_btnSubtract setBackgroundImage:[UIImage imageNamed:@"map_zoom_in"] forState:UIControlStateNormal] ;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(zomeSmall:)];
    tap.numberOfTapsRequired = 2;
    [_btnSubtract addGestureRecognizer:tap];
    [self.mapView addSubview:_btnSubtract];
    
    [_btnSubtract addTarget:self action:@selector(zomeSmall:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)zomeSmall:(id)sender{
    
[self.mapView zoom:1.4];
}
- (void)zomeBig:(id)sender
{
//    self.mapView.zoomScale = self.mapView.zoomScale * 1.4;
    [self.mapView doCollisionDetection];
    [self.mapView zoom:0.8];
    
}
-(void)addZoomAddButton{

    
    _startY = _startY + 45;
    _btnAdd = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [_btnAdd setBackgroundImage:[UIImage imageNamed:@"map_zoom_out"] forState:UIControlStateNormal] ;
    _btnAdd.backgroundColor = [UIColor whiteColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(zomeBig:)];
    tap.numberOfTapsRequired = 2;
    [_btnAdd addGestureRecognizer:tap];
    //self.mapView.maximumZoomScale=2.5;
    
    _btnAdd.frame = CGRectMake(kScreenWidth-50, _startY, 40, 40);
    [_btnAdd addTarget:self action:@selector(zomeBig:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.mapView addSubview:_btnAdd];
    
   
}



-(void)addLocationButton{
  
    _Locationbtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    [_Locationbtn setBackgroundImage:[UIImage imageNamed:@"ico_dingwei"] forState:UIControlStateNormal] ;
    _Locationbtn.backgroundColor = [UIColor whiteColor];
    [_Locationbtn addTarget:self action:@selector(gotoCurrentCenter) forControlEvents:UIControlEventTouchUpInside];
    _Locationbtn.frame = CGRectMake(10,_startY, 40, 40);
    [self.mapView addSubview:_Locationbtn];
    
   
    
}
#pragma mark- 点击定位点
-(void)gotoCurrentCenter{
    if(!isLoctioning){
        if (_currentLocationStyle == LocationBluetooth) {
        self.manager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
        }else{
            [self startWifiLocation:_currentLocationStyle];
        }
    }else{
        if (_locationOverLayer) {
            [UIView animateWithDuration:0.3 animations:^{
                NSLog(@"width = %f,height = %f",self.view.width,self.view.height);
                _locationOverLayer.view.center= self.view.center;
            }];
            
                [self.mapView moveToPoint:_locationOverLayer.worldPosition animated:YES duration:0.3];



        }
    }
}

#pragma mark-切换楼层相关的View和button事件
-(void)addFloorChangeButton{
    _startY =_startY - 90;
    _floorChangeButton = [[UIButton alloc]initWithFrame:CGRectMake(10, _startY, 40, 40)];
    //[_floorChangeButton addTarget:self action:@selector(floorButtonTarget:) forControlEvents:UIControlEventTouchUpInside];
    
   
    _floorChangeButton.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [_floorChangeButton setTitle:_currentFloorName forState:UIControlStateNormal];
    [_floorChangeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_floorChangeButton setBackgroundColor:[UIColor whiteColor]];
    [self.mapView addSubview:_floorChangeButton];
    _floorChangeButton.layer.borderColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1].CGColor;
    _floorChangeButton.layer.borderWidth = 1.0;
}

-(void)floorButtonTarget:(UIButton*)sender{

    if (_floorFlag) {

        [self changeFloorTableViewdisappear];
    }else{

        [self changeFloorTableViewappear ];
    }
}
-(void)changeFloorTableViewdisappear{
    _floorFlag = !_floorFlag;
    [UIView animateWithDuration:0.4 animations:^{
        _tableViewOfFloors.alpha = 1;
        _tableViewOfFloors.frame = CGRectMake( _floorChangeButton.frame.origin.x, _floorChangeButton.frame.origin.y, 40, 0);
    }];
}

-(void)changeFloorTableViewappear{
    _floorFlag = !_floorFlag;
    [UIView animateWithDuration:0.4 animations:^{
        
        _tableViewOfFloors.alpha = 1;
        
        if (_floorDataArray.count >5) {
            _tableViewOfFloors.frame = CGRectMake( _floorChangeButton.frame.origin.x, _floorChangeButton.frame.origin.y-45*5, 40, 45*5);
        }else{
             _tableViewOfFloors.frame = CGRectMake( _floorChangeButton.frame.origin.x, _floorChangeButton.frame.origin.y-45*_floorDataArray.count, 40, 45*_floorDataArray.count);
        }
    }];
}
-(void)addChangeFloorTableView{

    _tableViewOfFloors = [[UITableView alloc]initWithFrame:CGRectMake( _floorChangeButton.frame.origin.x, _floorChangeButton.frame.origin.y, 40, 0)];
    _tableViewOfFloors.backgroundColor = [UIColor whiteColor];
    _tableViewOfFloors.delegate = self;
    _tableViewOfFloors.dataSource = self;
    _tableViewOfFloors.separatorStyle =UITableViewCellSeparatorStyleSingleLine;
    _tableViewOfFloors.separatorColor = [UIColor whiteColor];
    _tableViewOfFloors.showsVerticalScrollIndicator = NO;
    _tableViewOfFloors.showsHorizontalScrollIndicator = NO;
    _tableViewOfFloors.userInteractionEnabled = YES;
    [self.mapView addSubview:_tableViewOfFloors];
}

#pragma mark-初始化地图的代码
-(void)addMapData{
    _NgrFeatureLayerLocation = [[NGRFeatureLayer alloc]initWithFeatureName:@"positioning"];
    
    NGRMapView* mapView = self.mapView;
    
    [mapView setMaxZoom:(0.1f)];
//    [mapView setMinZoom:(0.3f)];
    [mapView setMinAngle:(60)];
    
    [mapView addLayer:_NgrFeatureLayerLocation];
    
    //图层高度
    [_NgrFeatureLayerLocation setCoordinateOffset:mapView.coordinateOffset];
    
    [self.mapView registerGestures];

    if (!_dataSource) {
       // _dataSource = [[NGRDataSource alloc] initWithRoot:@"172.16.10.25:8080/nagrand-service/"];
        _dataSource = [[NGRDataSource alloc] init];
        _dataSource.delegate = self;
    }
    //    [_dataSource requestMaps];
    [_dataSource requestMap:6];
    //[_dataSource searchPOI:@"厕所" start:0 count:10 parents:nil categories:nil];
    self.mapView.delegate=self;
    [SVProgressHUD showWithStatus:@"加载地图中"];
}


#pragma mark- poi搜索的回调
-(void)didPOISearchRespond:(NSArray *)pois{
        [SVProgressHUD dismiss];
    if (!pois || pois.count == 0){
        [self addErrorMessage];
    }else{
//        [SVProgressHUD showSuccessWithStatus:@"success"];
        [_searchVC.navigationController popViewControllerAnimated:YES];
        
        [self.mapView removeAllOverlayer];
        [self.mapView addOverlayer:_locationOverLayer];
        
        for (NGRLocationModel *model in pois) {
            NGRFeature *feature = [self.mapView searchFeatureWithId:model.ID];
            if (!feature) {
                continue;
            }
            CGPoint point = [feature getCentroid];
            CGPoint screePoint =  [self.mapView getScreenPositionFromWorldPosition:point];
            UIImageView *imageView = [[UIImageView alloc]init];
            imageView.image = [UIImage imageNamed:@"定位"];
            imageView.frame = CGRectMake(screePoint.x, screePoint.y, 30, 30);
            imageView.center = screePoint;
            NGROverlayer *overLayer = [[NGROverlayer alloc]initWithView:imageView];
            overLayer.floorId = self.mapView.currentID;
            [self.mapView addOverlayer:overLayer];

            if (pois.count == 1) {
                [_realTimeView endNavigationAction:nil];
                if (!self.setStartAndEndPointView) {
                    [self addSetStartAndEndPointView];
                    [self MoveUp];
                }
                [self.mapView removeOverlayer:overLayer];
                self.setStartAndEndPointView.pinOverLayer = overLayer;
                [self.mapView moveToPoint:overLayer.worldPosition animated:YES duration:0.5];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.mapView resetOverlayers];
                    [self.mapView addOverlayer:overLayer];
                });
            }

        }
    }
}

-(void)didErrorOccurred:(NSError *)state{
    self.plottingView.changeAbled = NO;
    [SVProgressHUD showErrorWithStatus:@"服务器好像出问题了"];

    [self addErrorMessage];
    
}

-(void)addErrorMessage{
    UIImageView *tempImage = [_searchVC.view viewWithTag:1000];
    if  (tempImage){
        [tempImage removeFromSuperview];
    }
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, KWIDTH, KHEIGHT - 64)];
    imageView.image = [UIImage imageNamed:@"no_search"];
    imageView.tag = 1000;
    //[_tempView addSubview:imageView];
    [_searchVC.view addSubview:imageView];
    [_searchVC.view endEditing:YES];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    imageView.userInteractionEnabled = YES;
    [imageView addGestureRecognizer:tap];
//    CGSize size = CGSizeMake(44,44);
//    CGFloat gap = 20;
//    UIImageView *deleView =[[UIImageView alloc]initWithFrame:CGRectMake(KWIDTH - size.width - gap , gap, size.width, size.height)];
//    deleView.image = [UIImage imageNamed:@"ico_closs@2x"];
//    [imageView addSubview:deleView];
}

-(void)tapAction:(UITapGestureRecognizer *)tap{
    UIView *image = [_searchVC.view viewWithTag:1000];
    [image removeFromSuperview];
}

-(void)didMapRespond:(NGRMapModel *)map{
    [_dataSource  requestPoiChildren:map.poi];

}

- (void)didPoiChildrenRespond:(NSArray *)pois {
    for (NGRFloorModel* floor in pois) {
            if (floor.isDefault) {
                [self loadFloor:floor.ID];
                [_tableViewOfFloors reloadData];
            }
        [_floorDataArray addObject:floor.address];
        
        [_floorNumberDataArray addObject:[NSNumber numberWithInt:floor.ID]] ;
    }
//    [self loadFloor:1672];

}
- (void)didFloorsRespond:(NSArray *)floors{
    for (NGRFloorModel* floor in floors) {
//        if (floor.isDefault) {
//            [self loadFloor:floor.ID];
//        }
        [_floorDataArray addObject:floor.address];
   
        [_floorNumberDataArray addObject:[NSNumber numberWithInt:floor.ID]] ;
    }
    [self loadFloor:1672];
    [_tableViewOfFloors reloadData];
}
#pragma mark-加载地图

- (void)loadFloor:(NGRID)floor {
    
    
    
    [_activityView startAnimating];
    [_dataSource requestPlanarGraph:floor];
    _currentFloorId = floor;
}

#pragma mark-加载地图完毕


- (void)didPlanarGraphRespond:(NGRPlanarGraph *)planarGraph {
    self.plottingView.changeAbled = YES;
    [self startDraw:planarGraph];
    
//    [self.mapView setMaxZoom:0.1];
    [self startLocation:_currentLocationStyle];
    [AppDelegate sharedAppdelegate].isFirstStart = false;
    [_activityView stopAnimating];
    
    [SVProgressHUD showSuccessWithStatus:@"地图加载成功"];
    _currentLocationStyle = LocationHCAndPal;
   // _currentLocationStyle = LocationBluetooth;
    

}



//- (void)mapViewWillBeginZooming:(NGRMapView *)mapView touchPoint:(CGPoint)point{
//    
//}
//- (void)mapViewDidZoom:(NGRMapView *)mapView zoomIn:(BOOL)zoomIn touchPoint:(CGPoint)point{
//
//    
//    
//}

-(void)mapViewDidZoom:(NGRMapView *)mapView scale:(CGFloat)scale{
    self.plottingView.plottingDistance = [mapView pixelLengthFromRealDistance:self.plottingView.scaleNum];
}

//- (void)mapViewDidEndZooming:(NGRMapView *)mapView touchPoint:(CGPoint)point{
//    
//}
- (void)mapViewDidRotating:(NGRMapView *)mapView rotation:(CGFloat)rotation{
    
    [self.compassView compassViewRotateWithAngleFromNorth:mapView.angleFromNorth];
    if (_locationOverLayer) {
        _locationOverLayer.view.transform = CGAffineTransformMakeRotation( -mapView.angleFromNorth* M_PI/180 + _currentAngleDevice);
    }
    _currentAngleMap = -mapView.angleFromNorth* M_PI/180;
}


#pragma mark-uitableview的回调方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _floorDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"floors"];
   
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellName"];
        
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:103.0/255.0 green:147.0/255.0 blue:162.0/255.0 alpha:1];
        
         cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }
    UILabel* labelView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
            labelView.font = [UIFont systemFontOfSize:9];
    labelView.layer.borderColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1].CGColor;
    labelView.layer.borderWidth = 1;
    labelView.backgroundColor = [UIColor clearColor];
    [cell addSubview:labelView];
    labelView.text  =[NSString stringWithFormat:@"%@",_floorDataArray[indexPath.row]] ;
    labelView.textAlignment = NSTextAlignmentCenter;

    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_activityView startAnimating];
    if (tableView == _tableViewOfFloors ) {
        
        [self changeFloorTableViewdisappear] ;
        [_dataSource requestPlanarGraph:((NSNumber*)_floorNumberDataArray[indexPath.row]).integerValue];
         _currentFloorId = ((NSNumber*)_floorNumberDataArray[indexPath.row]).integerValue;
        [_floorChangeButton setTitle:[_floorDataArray objectAtIndex:indexPath.row]  forState:UIControlStateNormal];
    }
}


#pragma mark- 获得点击屏幕的位置

-(void)touchPoint:(CGPoint)point withFeature:(NGRFeature *)feature {
    
    if (!_setStartAndEndPointView && feature) {
        [self addSetStartAndEndPointView];
        [self MoveUp];
    }
    
    //设置点击的位置
    [_setStartAndEndPointView setTouchPoint:point];
    if (!feature) {
        if (isLoctioning) {
//            [_Locationbtn setBackgroundImage:[UIImage imageNamed:@"ico_dingwei"] forState:UIControlStateNormal] ;
//            [self stopBluetoothLocation];
//            [self stopWifiLocation];
        }
        [self.mapView removeOverlayer:_setStartAndEndPointView.pinOverLayer];
        _setStartAndEndPointView.pinOverLayer = nil;
        if (!_setStartAndEndPointView.startPointOverLayer && !_setStartAndEndPointView.endPointOverLayer) {
            [_setStartAndEndPointView removeSetStartAndEndPointView];
            _setStartAndEndPointView = nil;
            [self MoveDown];
        }
    }

}


-(void)navigationViewAppear{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _navigationView.alpha = 1;
        _navigationView.transform = CGAffineTransformMakeScale(1, 1);
        
    }];
    
    
}


-(void)navigationViewDisappear:(BOOL)animate{
    
    if (animate) {
        
        [UIView animateWithDuration:0.5 animations:^{
            _navigationView.alpha = 0;
            
        }];
    }else{
        _navigationView.alpha = 0;
    }
    
}
#pragma mark - navigation 导航的代理

- (void)didNavigationRespond:(NGRFeatureCollection *)featureCollection {
    if (!featureCollection) {
        [SVProgressHUD dismiss];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"获取数据失败" message:@"是否重新获取数据" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alert.delegate = self;
        alert.tag = 101;
        [alert show];
        return;
    }
    [_naviLayer clearFeatures];
    [SVProgressHUD dismiss];
//    [SVProgressHUD showSuccessWithStatus:@"成功"];
    NSInteger count = [_navigationManager getPointCount:featureCollection];
   CGPoint startP =  [_navigationManager getPointFromFeatureCollection:featureCollection atIndex:0];
   CGPoint endP = [_navigationManager getPointFromFeatureCollection:featureCollection atIndex:count - 1];
    
    [self.setStartAndEndPointView changeLocationAboutStartAndEndPoint:startP and:endP];
        if (!_naviLayer) {
    _naviLayer = [[NGRFeatureLayer alloc] initWithFeatureName:@"navigate"];
    [_naviLayer setCoordinateOffset:self.mapView.coordinateOffset];
    [self.mapView addLayer:_naviLayer];
    
        }
    
    [_naviLayer addFeatures:featureCollection];
    
    NSLog(@"%f",_navigationManager.navigationTotalLineLength);
    [_realTimeView setDistanceFromEndPoint:_navigationManager.navigationTotalLineLength];
    
    [self addRealTime];
    
    [_realTimeView setDistanceFromEndPoint:_navigationManager.navigationTotalLineLength];
}

-(void)didNavigationRequestError:(NGRResourceState)state{
    [SVProgressHUD dismiss];
//    UNSUPPORTED_PROTOCOL,	//不支持协议
//    COULDNT_CONNECT,		//连接失败
//    REMOTE_ACCESS_DENIED,	//访问被拒绝
//    HTTP_RETURNED_ERROR,	//Http返回错误
//    READ_ERROR,				//读本地文件错误
//    UNKNOWN_ERROR,          //未知错误
//    OPERATION_TIMEDOUT      //timeout
    NSDictionary *dic = @{[NSNumber numberWithInteger:1]:@"不支持协议",
                          [NSNumber numberWithInteger:2]:@"连接失败",
                          [NSNumber numberWithInteger:3]:@"访问被拒绝",
                          [NSNumber numberWithInteger:4]:@"Http返回错误",
                          [NSNumber numberWithInteger:5]:@"读本地文件错误",
                          [NSNumber numberWithInteger:6]:@"未知错误",
                          [NSNumber numberWithInteger:7]:@"timeout",
                          };
    
    //NSString *tempStr = [NSString stringWithFormat:@"获取数据失败%@",[dic objectForKey:[NSNumber numberWithInt:state]]];[dic objectForKey:[NSNumber numberWithInt:state]];
    NSString *tempStr = @"获取数据失败";
    UIAlertView *alt = [[UIAlertView alloc]initWithTitle:@"提示" message:tempStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alt.tag = 100;
    alt.delegate = self;
    [alt show];

    
}

#pragma mark- UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 100) {
        [_setStartAndEndPointView removeSetStartAndEndPointView];
        [self MoveDown];
        _setStartAndEndPointView = nil;
    }
    if(alertView.tag == 101){
        if(buttonIndex == 0){
            NSLog(@"否");
            [_setStartAndEndPointView removeSetStartAndEndPointView];
            [self MoveDown];
            _setStartAndEndPointView = nil;
            
        }else if (buttonIndex == 1){
            NSLog(@"是");
            [SVProgressHUD showWithStatus:@"正在搜索"];
            NSLog(@"%f***id= %lld------%f***id = %lld",self.setStartAndEndPointView.startPointOverLayer.worldPosition,self.setStartAndEndPointView.startPointOverLayer.floorId,self.setStartAndEndPointView.endPointOverLayer.worldPosition,self.setStartAndEndPointView.endPointOverLayer.floorId);
            [_navigationManager navigationFromPoint:self.setStartAndEndPointView.startPointOverLayer.worldPosition fromFloor:self.setStartAndEndPointView.startPointOverLayer.floorId toPoint:self.setStartAndEndPointView.endPointOverLayer.worldPosition toFloor:self.setStartAndEndPointView.endPointOverLayer.floorId];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                sleep(1);
            });
        }
    }

}

#pragma mark- 双击手势

-(void)tapGestureCreate{
    _tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleClick:)];
    _tapGesture.numberOfTapsRequired = 2;
    _tapGesture.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:_tapGesture];
}
//static bool isScale;
-(void)doubleClick:(UIGestureRecognizer *)tapGesture{
    CGPoint point = [tapGesture locationInView:self.mapView];
//    if (isScale) {
//            [self.mapView zoom:2.0];
//        isScale = NO;
//    }else{
//        isScale = YES;
//        [self.mapView zoom:0.5];
//    }
    [self.mapView zoom:1.2];

//    [self.mapView resetOverlayers];
    NSLog(@"双击了一次 位置是%@",NSStringFromCGPoint(point));
}




-(void)selectPoiPublicFaciting:(UIButton*)sender{
    [self.mapView visibleAllLayerFeature:@"Facility" isVisible:NO];
    switch (sender.tag) {
        case 1:{
            static BOOL flag;
            [self.mapView visibleAllLayerFeature:@"Facility" isVisible:YES];
            if (flag) {
                
                [ UIView animateWithDuration:0.5 animations:^{
                    _publicFacilitiesView.frame = CGRectMake(kScreenWidth - 50, 50, 38, 83);
                }];
            }else{
                
                [ UIView animateWithDuration:0.5 animations:^{
                    _publicFacilitiesView.frame = CGRectMake(kScreenWidth - 50, 50, 38, 374);
                }];
            }
            flag = !flag;
            
        }
            
            break;
        case 2:
        {
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(24091000) isVisible:YES];
        }
            
            break;
        case 3:
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(24093000) isVisible:YES];
            break;
        case 4:
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(23061000) isVisible:YES];
            break;
        case 5:
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(24097000) isVisible:YES];
            break;
        case 6:
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(23024000) isVisible:YES];
            [self.mapView visibleLayerFeature:@"Facility" key:@"category" value:@(23025000) isVisible:YES];
            
            break;
        case 7:
            [self.mapView visibleAllLayerFeature:@"Facility" isVisible:YES];
            break;
        default:
            break;
    }
    
}


#pragma mark- 添加定位引擎切换视图
//-(void)createTmepView{
//    _tempView = [[tempView alloc]initWithFrame:CGRectMake(20, 130,[UIScreen mainScreen].bounds.size.width-40, 400)];
//    __weak typeof(_tempView)weakTempView = _tempView;
//    __weak typeof(self)weakSelf = self;
//    __weak typeof(_locationOverLayer)weakLocationOverLayer = _locationOverLayer;
//    [_tempView setCurrentLocationStyle:_currentLocationStyle];
//    _tempView.myblock = ^(LocationStyle style){
//        if ((int)style != -1) {
//            [SVProgressHUD showSuccessWithStatus:@"切换成功,请重启定位"];
//            [weakSelf stopBluetoothLocation];
//            [weakSelf stopWifiLocation];
//            _currentLocationStyle = style;
//            [weakTempView setCurrentLocationStyle:style];
////            if (style == LocationBluetooth) {
////                    weakSelf.manager = [[CBPeripheralManager alloc]initWithDelegate:weakSelf queue:nil];
////            }else{
////            //[weakSelf startWifiLocation:style];
////            }
//        }
//        _tempView = nil;
//    };
//    [self.view addSubview:_tempView];
//}

-(void)clickTap:(UIControl *)con{
    NSLog(@"%ld",con.tag);
}

//添加实时导航视图
#pragma mark-添加实时导航视图
-(void)addRealTime{
    __weak typeof(self)weakSelf = self;
    __weak typeof(_naviLayer)weakNaviLayer = _naviLayer;
    _realTimeView= [[RealTimeNavigationView alloc]initWithFrame:CGRectMake(0, KHEIGHT, KWIDTH, 64)];
//    [_realTimeView setDistanceFromEndPoint:20];
    _realTimeView.endNavBlock = ^{
        [weakSelf MoveDown];
        [weakSelf.setStartAndEndPointView removeSetStartAndEndPointView];
        weakSelf.setStartAndEndPointView = nil;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakNaviLayer clearFeatures];
        });
    };
    [self.view addSubview:_realTimeView];
    [UIView animateWithDuration:0.3 animations:^{
        _realTimeView.frame = CGRectMake(0, KHEIGHT - 64, KWIDTH, 64);
    }];
    
}
/*
LocationProbeAndPal = 1,
LocationHCAndPal,
LocationHCAndYJ,
LocationBETAndPal,
LocationBluetooth
 */

#pragma mark- 开始定位
-(void)startLocation:(LocationStyle)style{
    if (style == LocationBluetooth) {
        self.manager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
    }else{
        [self startWifiLocation:style];
    }
}

#pragma mark- 结束定位
-(void)stopLocation{
    [self stopWifiLocation];
    [self stopBluetoothLocation];
    [SVProgressHUD showSuccessWithStatus:@"切换成功,请重启定位"];
}

#pragma mark- 开始wifi定位
-(void)startWifiLocation:(LocationStyle)style{
    isLoctioning = YES;
//    [_Locationbtn setBackgroundImage:[UIImage imageNamed:@"ico_dingwei_pre"] forState:UIControlStateNormal] ;
    if (!_wifiManager) {
        [SVProgressHUD showSuccessWithStatus:@"开始定位"];
    }
    LocationStyle location1 = LocationProbeAndPal;
    LocationStyle location2 = LocationHCAndPal;
    LocationStyle location3 = LocationHCAndYJ;
    LocationStyle location4 = LocationBETAndPal;
    NSDictionary *dic =
  @{[NSNumber numberWithInt:location1]:LOCATIONKEYPROBEANDPAL,
    [NSNumber numberWithInt:location2]:LOCATIONKEYHCANDPAL,
    [NSNumber numberWithInt:location3]:LOCATIONKEYHCANDYJ,
    [NSNumber numberWithInt:location4]:LOCATIONKEYBETANDPAL};
    //MACADDRESS要传本机的Mac地址  ->设置->通用->关于本机->无线局域网地址
    if (_wifiManager) {
        _wifiManager.delegate = nil;
        _wifiManager = nil;
    }
    NSString *mac = [AppDelegate sharedAppdelegate].macAddress;
    if (mac) {
        _wifiManager = [[NGRPositioningManager alloc]initWithMacAddress:mac appKey:[dic objectForKey:[NSNumber numberWithInt:style]]];
    }else{
        _wifiManager = [[NGRPositioningManager alloc]initWithMacAddress:MACADDRESS appKey:[dic objectForKey:[NSNumber numberWithInt:style]]];
    }

    NSLog(@"---切换定位方式");
    _wifiManager.delegate = self;
    [_wifiManager start];


}

-(void)stopWifiLocation{
    if (_wifiManager) {
        _wifiManager.delegate = nil;
        _wifiManager = nil;
    }
    if (_locationOverLayer) {
        [self.mapView removeOverlayer:_locationOverLayer];
        //[SVProgressHUD showSuccessWithStatus:@"结束定位"];
        _locationOverLayer = nil;
    }
    [_Locationbtn setBackgroundImage:[UIImage imageNamed:@"ico_dingwei"] forState:UIControlStateNormal] ;
    isLoctioning = NO;
}

#pragma mark- 开始蓝牙定位
-(void)startBluetoothLocation{
    
    isLoctioning = YES;
    if(!_blueManager){
    [SVProgressHUD showSuccessWithStatus:@"开始定位"];
    }
//    [_Locationbtn setBackgroundImage:[UIImage imageNamed:@"ico_dingwei_pre"] forState:UIControlStateNormal] ;
    if (_blueManager) {
        [_blueManager stopBLE];
        _blueManager = nil;
    }
    _blueManager = [[NGRPositioningManager alloc]initWithLicense:@"4da2b7f1e5114ba4977e5b165289bc30" mapID:BLUELOCATIONID];
    //_blueManager = [[NGRPositioningManager alloc]initWithLicense:APPKEY mapID:BLUELOCATIONID];
    _blueManager.delegate = self;
    [_blueManager startBLE];
}

-(void)stopBluetoothLocation{
    if (_blueManager) {
        [_blueManager stopBLE];
        _blueManager = nil;
    }
    if (_locationOverLayer) {
        [self.mapView removeOverlayer:_locationOverLayer];
        _locationOverLayer = nil;
        //[SVProgressHUD showSuccessWithStatus:@"结束定位"];
    }
        [_Locationbtn setBackgroundImage:[UIImage imageNamed:@"ico_dingwei"] forState:UIControlStateNormal] ;
    isLoctioning = NO;
}

#pragma mark- NGRPositioningDelegate
-(void)didLocationChanged:(NGRLocation *)oldLocation newLocation:(NGRLocation *)newLocation{
//    [self.mapView moveToPoint:newLocation.point animated:YES duration:.5];
    [_Locationbtn setBackgroundImage:[UIImage imageNamed:@"ico_dingwei_pre"] forState:UIControlStateNormal];
    if (!_locationOverLayer) {
        UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
        imageV.image = [UIImage imageNamed:@"locationPoint"];
        imageV.center = [self.mapView getScreenPositionFromWorldPosition:newLocation.point];
        _locationOverLayer =[[NGROverlayer alloc]initWithView:imageV];
        [self.mapView addOverlayer:_locationOverLayer];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            _locationOverLayer.view.center = [self.mapView getScreenPositionFromWorldPosition:newLocation.point];
        }];
        _locationOverLayer.worldPosition = newLocation.point;
    }
    [self.mapView resetOverlayers];
}

-(void)didLocationError:(enum NGRResourceState)state{
    [SVProgressHUD showErrorWithStatus:@"定位数据获取失败"];
}

#pragma mark -蓝牙定位回调
-(void)didDownloadDatabaseSuccess{
//    [SVProgressHUD showSuccessWithStatus:@"拉取蓝牙数据库成功"];
}

-(void)didDownloadDatabaseError{
    [SVProgressHUD showErrorWithStatus:@"拉取蓝牙数据库失败"];
}
- (void)dealloc
{
        _dataSource.delegate = nil;
}

#pragma mark- 检测蓝牙是否开启的代理
-(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    switch (peripheral.state) {
        case CBPeripheralManagerStatePoweredOn:
        {
            NSLog(@"蓝牙开启且可用");
//            [_tempView setCurrentLocationStyle:_currentLocationStyle];
            [self startBluetoothLocation];
        }
            break;
            
        default:
            NSLog(@"蓝牙不可用");
            break;
    }
}



#pragma mark- CLLocationManagerDelegate
-(void)createcollectionManger{
    self.cllocationManger = [[CLLocationManager alloc]init];
    self.cllocationManger.delegate = self;
    if ([CLLocationManager headingAvailable]) {
        [self.cllocationManger startUpdatingHeading];
    }else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"atention" message:@"compass not Available" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
    }
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"%@",[error description]);
}

-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{
    
    
    _locationOverLayer.view.transform = CGAffineTransformMakeRotation((newHeading.magneticHeading + 45) * M_PI/180 + _currentAngleMap);
    _currentAngleDevice = (newHeading.magneticHeading + 45) * M_PI/180;

}

-(BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manage{
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"内存警告！");
    // Dispose of any resources that can be recreated.
}
@end
